package com.jml.zlhq.app.ui;

import java.util.HashMap;
import java.util.Map;

import net.youmi.android.AdManager;
import net.youmi.android.offers.OffersManager;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.dow.android.DOW;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.thirdlogin.OnLoginListener;
import cn.sharesdk.wechat.friends.Wechat;
import cn.waps.AppConnect;

import com.bb.dd.BeiduoPlatform;
import com.jml.zlhq.app.AppConfig;
import com.jml.zlhq.app.AppContext;
import com.jml.zlhq.app.BuildConfig;
import com.jml.zlhq.app.R;
import com.jml.zlhq.app.URLs;
import com.jml.zlhq.app.service.HttpService;
import com.jml.zlhq.app.util.BaseTools;
import com.jml.zlhq.app.util.MD5;
import com.jml.zlhq.app.util.StringUtil;
import com.jml.zlhq.app.util.UIUtil;
import com.loopj.android.http.TextHttpResponseHandler;
import com.yql.dr.sdk.DRSdk;

public class LoginActivity extends BaseActivity implements Callback, PlatformActionListener{
	private TextView forgetPass,msg,thirdQq,thirdWeb;
	private EditText userid,passwd;
	private Button submit,register;
	
	private static final int MSG_AUTH_CANCEL = 2;
	private static final int MSG_AUTH_ERROR= 3;
	private static final int MSG_AUTH_COMPLETE = 4;
	
	
	@SuppressWarnings("unused")
	private OnLoginListener signupListener;
	private Handler handler;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_activity);
		
		LinearLayout leftLay = (LinearLayout) findViewById(R.id.content_header_left_lay);
		//LinearLayout rightLay = (LinearLayout) findViewById(R.id.content_header_right_lay);
		leftLay.setOnClickListener(this);
		//rightLay.setOnClickListener(this);
		AutoCompleteTextView centerEdit = (AutoCompleteTextView) findViewById(R.id.content_header_center_edit);
		centerEdit.setVisibility(View.GONE);
		ImageView leftImage = (ImageView) findViewById(R.id.content_header_left_img);
		leftImage.setImageResource(R.drawable.back_selector);
		ImageView roghtImage1 = (ImageView) findViewById(R.id.content_header_right_img);
		roghtImage1.setVisibility(View.GONE);
		TextView centerText = (TextView) findViewById(R.id.content_header_center_text);
		centerText.setText("登录");
		TextView rightText = (TextView) findViewById(R.id.content_header_right_text);
		rightText.setText("  ");
		TextView cityChosed = (TextView) findViewById(R.id.content_header_center_text2);
		cityChosed.setVisibility(View.GONE);
		
		handler = new Handler(this);
		
		thirdWeb = (TextView) findViewById(R.id.third_login_zlhqweb);
		thirdQq = (TextView) findViewById(R.id.third_login_qq);
		
		forgetPass = (TextView) findViewById(R.id.login_forgetpassword);
		msg = (TextView) findViewById(R.id.login_msg);
		userid = (EditText) findViewById(R.id.login_userid);
		passwd = (EditText) findViewById(R.id.login_passwd);
		submit = (Button) findViewById(R.id.login_submit);
		register = (Button) findViewById(R.id.login_register);
		register.setOnClickListener(this);
		forgetPass.setOnClickListener(this);
		submit.setOnClickListener(this);
		thirdQq.setOnClickListener(this);
		thirdWeb.setOnClickListener(this);
		
//		userid.setOnFocusChangeListener(new OnFocusChangeListener() {
//			@Override
//			public void onFocusChange(View v, boolean hasFocus) {
//				Drawable drawable1 = getResources().getDrawable(hasFocus?R.drawable.loginico_user_hover:R.drawable.loginico_user);
//				drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight()); 
//				((EditText)v).setCompoundDrawables(drawable1, null, null, null);
//			}
//		});
//		passwd.setOnFocusChangeListener(new OnFocusChangeListener() {
//			@Override
//			public void onFocusChange(View v, boolean hasFocus) {
//				Drawable drawable1 = getResources().getDrawable(hasFocus?R.drawable.loginico_password_hover:R.drawable.loginico_password);
//				drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight()); 
//				((EditText)v).setCompoundDrawables(drawable1, null, null, null);
//			}
//		});
	}

	@Override
	public void loadData(Map<String, String> param) {}

	@Override
	public void clearData() {}
	
	public void setOnLoginListener(OnLoginListener l) {
		this.signupListener = l;
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode==201&&appContext.isLogin()){
			finish();	
		}
		if(requestCode==202&&appContext.isLogin()){
			finish();	
		}
		if(requestCode==203&&appContext.isLogin()){
			String phone = BaseTools.getFrom("phone", appContext.getLoginUser());
			if(StringUtil.isEmpty(phone)||"null".equals(phone)){
				UIUtil.openActivity(activity, BindPhoneActivity.class, null,204);
			}else{
				finish();
			}
		}
		if(requestCode==204&&appContext.isLogin()){
			finish();
		}
	}

	@Override
	public void onClick(View view) {
		final String userId = userid.getText().toString();
		final String pass = passwd.getText().toString();
		switch (view.getId()) {
		case R.id.content_header_left_lay:
			finish();
			break;
		case R.id.login_forgetpassword:
			Bundle phoneBd = new Bundle();
			phoneBd.putString("phone", !StringUtil.isEmpty(userId)&&StringUtil.isPhone(userId)?userId:null);
			UIUtil.openActivity(this, NewPassWordActivity.class, phoneBd, 201);
			break;
		case R.id.login_register:
			UIUtil.openActivity(this, RegisterActivity.class, null, 202);
			break;
		case R.id.third_login_qq:
			Platform qq= ShareSDK.getPlatform(this, QQ.NAME);
			authorize(qq);
			break;
		case R.id.third_login_zlhqweb:
			UIUtil.openActivity(this, WebLoginActivity.class, null, 203);
			break;
		case R.id.login_submit:
			try{
			if(StringUtil.isEmpty(userId)){
				msg.setText("登录账号不能为空");
			/*}else if(!StringUtil.isPhone(userId)){
				msg.setText("手机号不正确");*/
			}else if(StringUtil.isEmpty(pass)){
				msg.setText("登录密码不能为空");
			}else{
				final Map<String, String> sbmap = new HashMap<String, String>();
				sbmap.put("user", userId);
				sbmap.put("password", MD5.MD5Encode(pass));
				/*final Handler mHandler = new Handler(){
					@Override
					public void handleMessage(Message msg) {
						switch (msg.what) {
						case 1:
							afterLogined(activity);
							String isfirst = BaseTools.getFrom("isFirstLogin", appContext.getLoginUser(), "false");
							if(isfirst=="true"){
								final CommonDialog show = new CommonDialog(activity, false);
								show.show(true, true, false, "欢迎使用", "欢迎使用赚零花钱，您已经获得50金币奖励，祝您赚零花钱愉快！", "领取", "", new OnClickListener(){
									@Override
									public void onClick(View v) {
										show.dismiss();
										finish();
									}
								}, null);
							}else{
								finish();
							}
							break;
						default:
							break;
						}
					}
				};*/
				final Dialog  mProDialog =  UIUtil.showLoadingDialog(activity, "登录中，请稍后...", false);
				HttpService.postByText(URLs.USER_LOGIN_SUBMIT, sbmap, new TextHttpResponseHandler() {
							@Override
							public void onSuccess(int arg0, Header[] arg1, String result) {
								mProDialog.dismiss();
								try {
									JSONObject json = new JSONObject(result);
									Log.i("==vcode==", result);
									if (BaseTools.getFrom("status", json).equals("0")) {
										appContext.Login(json.getJSONObject("data").toString());
										afterLogined(activity,new CheckBind() {
											@Override
											public void checkBind(String phone) {
												LoginActivity.this.finish();
												/*if(StringUtil.isEmpty(phone)||!StringUtil.isPhone(phone)){
													UIUtil.openActivity(activity, BindPhoneActivity.class, null,204);
												}else{
													LoginActivity.this.finish();
												}*/
											}
										});
										//LoginActivity.this.finish();
										//\mHandler.sendEmptyMessage(1);
									} else{
										msg.setText(BaseTools.getFrom("message", json));
									}
								} catch (JSONException e) {
									e.printStackTrace();
								} catch (Exception e) {
									e.printStackTrace();
								}
							}

							@Override
							public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
								mProDialog.dismiss();
								msg.setText("访问错误");
							}
						});
			}
			} catch (Exception e1) {
				msg.setText("系统错误：加密失败！");
			}
			break;
		default:
			break;
		}
	}

	private void authorize(Platform plat) {
//		if(plat.isValid()) {
//			String userId = plat.getDb().getUserId();
//			if (!TextUtils.isEmpty(userId)) {
//				handler.sendEmptyMessage(MSG_AUTH_CANCEL);
//				return;
//			}
//		}
		plat.setPlatformActionListener(this);
		//关闭SSO授权
		//plat.SSOSetting(true);
		//plat.isClientValid()
		plat.SSOSetting(false);
		//plat.authorize();
		//plat.showUser(null);
		//if(!plat.isValid()){
		//plat.authorize();
		plat.showUser(null);
		//}
	}

	@Override
	public void onComplete(Platform platform, int action, HashMap<String, Object> res) {
		Log.i("==third login==", new JSONObject(res).toString());
		if (action == Platform.ACTION_USER_INFOR) {
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("id", platform.getDb().getUserId());
			map.put("name", platform.getDb().getUserName());
			map.put("image", platform.getDb().getUserIcon());
			map.put("gender", platform.getDb().getUserGender());
			Message msg = new Message();
			msg.what = MSG_AUTH_COMPLETE;
			msg.obj = new Object[] {platform.getName(), map, res};
			handler.sendMessage(msg);
		}
	}
	
	@Override
	public void onError(Platform platform, int action, Throwable t) {
		t.printStackTrace();
		platform.removeAccount();
		if (action == Platform.ACTION_USER_INFOR) {
			handler.sendEmptyMessage(MSG_AUTH_ERROR);
		}
		t.printStackTrace();
	}
	
	@Override
	public void onCancel(Platform platform, int action) {
		Log.i("==third login==", "cancel");
		if (action == Platform.ACTION_USER_INFOR) {
			handler.sendEmptyMessage(MSG_AUTH_CANCEL);
		}
		platform.removeAccount();
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public boolean handleMessage(Message msg) {
		switch(msg.what) {
			case MSG_AUTH_CANCEL: {
				//取消授权
				Toast.makeText(activity, R.string.auth_cancel, Toast.LENGTH_SHORT).show();
			} break;
			case MSG_AUTH_ERROR: {
				//授权失败
				Toast.makeText(activity, R.string.auth_error, Toast.LENGTH_SHORT).show();
			} break;
			case MSG_AUTH_COMPLETE: {
				//授权成功
				//Toast.makeText(activity, R.string.auth_complete, Toast.LENGTH_SHORT).show();
				Object[] objs = (Object[]) msg.obj;
				String platform = (String) objs[0];
				
				HashMap<String, String> user = (HashMap<String, String>) objs[1];
				HashMap<String, Object> res = (HashMap<String, Object>) objs[2];
				
				
				final Map<String, String> post = new HashMap<String, String>();
				if(!StringUtil.isEmpty(platform)&&platform.equals(SinaWeibo.NAME)){
					post.put("id",user.get("id"));
					post.put("image", user.get("image"));
					post.put("name", user.get("name"));
					post.put("gender", user.get("gender"));
					
					post.put("oauth_source", "WEIBO");
					post.put("locate", BaseTools.getFrom("location", res));
					post.put("province", BaseTools.getFrom("province", res));
					post.put("city", BaseTools.getFrom("city", res));
					post.put("description", BaseTools.getFrom("description", res));
				}
				if(!StringUtil.isEmpty(platform)&&platform.equals(QQ.NAME)){
					post.put("id",user.get("id"));
					post.put("image", user.get("image"));
					post.put("name", user.get("name"));
					post.put("gender", user.get("gender"));
					
					post.put("oauth_source", "QQ");
					post.put("locate", BaseTools.getFrom("province", res)+"-"+BaseTools.getFrom("city", res));
					post.put("province", BaseTools.getFrom("province", res));
					post.put("city", BaseTools.getFrom("city", res));
					post.put("description", "");
				}
				if(!StringUtil.isEmpty(platform)&&platform.equals(Wechat.NAME)){
					post.put("id",user.get("id"));
					post.put("image", user.get("image"));
					post.put("name", user.get("name"));
					post.put("gender", user.get("gender"));
					
					post.put("oauth_source", "WEIXIN");
					post.put("locate", BaseTools.getFrom("province", res)+"-"+BaseTools.getFrom("city", res));
					post.put("province", BaseTools.getFrom("province", res));
					post.put("city", BaseTools.getFrom("city", res));
					post.put("description", "");
				}
				ClipboardManager c= (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
				ClipData clip = ClipData.newPlainText("third", new JSONObject(post).toString());
				c.setPrimaryClip(clip);
				final Dialog  mProDialog =  UIUtil.showLoadingDialog(activity, "登录中，请稍后...", false);
				HttpService.postByText(URLs.USER_THIRD_LOGIN, post, new TextHttpResponseHandler() {
					
					@Override
					public void onSuccess(int arg0, Header[] arg1, String result) {
						mProDialog.dismiss();
						try {
							JSONObject json = new JSONObject(result);
							Log.i("==vcode==", result);
							ClipboardManager c= (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
							ClipData clip = ClipData.newPlainText("third", result);
							c.setPrimaryClip(clip);
							if(BaseTools.getFrom("status", json).equals("0")){
								appContext.Login(json.getJSONObject("data").toString());
								afterLogined(activity,new CheckBind() {
									@Override
									public void checkBind(String phone) {
										/*if(StringUtil.isEmpty(phone)||!StringUtil.isPhone(phone)){
											UIUtil.openActivity(activity, BindPhoneActivity.class, null,204);
										}*/
									}
								});
								finish();
							}else{
								LoginActivity.this.msg.setText(BaseTools.getFrom("message", json));
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					
					@Override
					public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
						mProDialog.dismiss();
						UIUtil.ToastMessage(activity, "登录失败，请稍后重试");
					}
				});
				
			} break;
			
		}
		return false;
	}
	
	public static void login(final String userId, String pass, final Activity activity, final AfterDo after){
		final AppContext appContext = (AppContext) activity.getApplication();
		final Map<String, String> sbmap = new HashMap<String, String>();
		sbmap.put("user", userId);
		sbmap.put("password", pass);
		/*final Handler mHandler = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 1:
					afterLogined(activity);
					String isfirst = BaseTools.getFrom("isFirstLogin", appContext.getLoginUser(), "false");
					if(isfirst=="true"){
						final CommonDialog show = new CommonDialog(activity, false);
						show.show(true, true, false, "欢迎使用", "欢迎使用赚零花钱，您已经获得50金币奖励，祝您赚零花钱愉快！", "领取", "", new OnClickListener(){
							@Override
							public void onClick(View v) {
								show.dismiss();
								if(after!=null)after.afterDo(activity);
							}
						}, null);
					}else{
						if(after!=null)after.afterDo(activity);
					}
					break;
				default:
					break;
				}
			}
		};*/
		final Dialog  mProDialog =  UIUtil.showLoadingDialog(activity, "登录中，请稍后...", false);
		HttpService.postByText(URLs.USER_LOGIN_SUBMIT, sbmap,
				new TextHttpResponseHandler() {
					@Override
					public void onSuccess(int arg0, Header[] arg1, String result) {
						mProDialog.dismiss();
						try {
							JSONObject json = new JSONObject(result);
							Log.i("==vcode==", result);
							if (BaseTools.getFrom("status", json).equals("0")) {
								appContext.Login(json.getJSONObject("data").toString());
								afterLogined(activity,null);
								if(after!=null)after.afterDo(activity);
								//mHandler.sendEmptyMessage(1);							
							} 
						} catch (JSONException e) {
							e.printStackTrace();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
						mProDialog.dismiss();
					}
				});
	}
	
	
	
	public static void afterLogined(Context context,CheckBind checkBind){
		WodeFragment.freshPage = true;
//		TanDianFragment.freshPage = true;
//		LingGanFragment.freshPage = true;
//		MainActivity.fragementFreash();
		
		AppContext appContext = (AppContext)context.getApplicationContext();
		userInfo(appContext,checkBind);
		//pushPoint(appContext);
	}
	
	public static void userInfo(final AppContext appContext,final CheckBind checkBind){
		final Handler handler = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				MainActivity.fragementFreash();
			}
		};
		if(appContext.isLogin()){
			final Map<String, String> param = new HashMap<String, String>();
			param.put("auth_token", appContext.getLoginUid());
			HttpService.getByText(URLs.USER_INFO, param, new TextHttpResponseHandler() {
				@Override
				public void onSuccess(int arg0, Header[] arg1, String resultStr) {
					try {
						if(BuildConfig.DEBUG)Log.i("==result post==", resultStr);
						JSONObject result = new JSONObject(resultStr);
						if(result.getInt("status")==0){
							JSONObject data = result.getJSONObject("data");
							data.put("auth_token",appContext.getLoginUid());
							appContext.Login(data.toString());
							handler.sendEmptyMessage(1);
							if(checkBind!=null)checkBind.checkBind(BaseTools.getFrom("phone", data));
						}else{
							checkBind.checkBind(BaseTools.getFrom("status", result));
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
				
				@Override
				public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
					//UIUtil.ToastMessage(activity, "抱歉，访问失败");
				}
			});
		}else{
			WodeFragment.freshPage = true;
			handler.sendEmptyMessage(1);
		}
	}
	
//	public static void pushPoint(final AppContext appContext){
//		
//		final SharedPreferences sharedPreferences = appContext.getSharedPreferences("POINT_ADD", Context.MODE_PRIVATE);   
//		final int point = sharedPreferences.getInt("point",0);
//		if(point<=0)return;
//		Editor edit = sharedPreferences.edit();
//		edit.putInt("point",0);
//		edit.commit();
//		final MFload jb = new MFload(point);
//		final Map<String, String> sbmap = new HashMap<String, String>();
//		sbmap.put("access-token", appContext.getLoginUid());
//		sbmap.put("coinnum", String.valueOf(point));
//		HttpService.postByText(URLs.USER_POINT_ADD, sbmap, new TextHttpResponseHandler() {
//					@Override
//					public void onSuccess(int arg0, Header[] arg1, String result) {
//						try {
//							JSONObject json = new JSONObject(result);
//							Log.i("==vcode==", result);
//							if (BaseTools.getFrom("status", json).equals("0")) {
//								Log.e("==loggin add 金币==", jb.getF()+"");
//								jb.setF(0);
//								afterLogined(appContext);
//								return;
//							} 
//						} catch (Exception e) { }
//						Editor edit2 = sharedPreferences.edit();
//						edit2.putInt("point",(int)jb.getF()+sharedPreferences.getInt("point",0));
//						edit2.commit();
//					}
//
//					@Override
//					public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
//						Editor edit2 = sharedPreferences.edit();
//						edit2.putInt("point",(int)jb.getF()+sharedPreferences.getInt("point",0));
//						edit2.commit();
//					}
//				});
//		
//	}
	
	public interface AfterDo{
		public void afterDo(Activity activity);
	}
	
	public interface CheckBind{
		public void checkBind(String phone);
	}
}
